package com.sec.security.service.impl;

import java.io.File;
import java.util.Optional;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import com.sec.base.utils.AesFileUtil;
import com.sec.base.utils.AjaxJson;
import com.sec.base.utils.FileUtil;
import com.sec.base.utils.SecurityUtil;
import com.sec.history.dao.HistoryDao;
import com.sec.history.entity.History;
import com.sec.history.service.HistoryService;
import com.sec.security.service.SecurityService;
import com.sec.user.entity.User;

@Service("securityService")
@Transactional
public class SecurityServiceImpl implements SecurityService {
	private Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);

	@Autowired
	private HistoryService historyService;
	@Autowired
	private HistoryDao historyDao;

	@Override
	public AjaxJson encryptTxt(HttpServletRequest request, String originalText, String password) {
		AjaxJson j = new AjaxJson();
		j.setCode("failure");
		j.setMsg("文字加密失败");
		try {
			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				j.setMsg("请登录");
				return j;
			}
			String encryptStr = SecurityUtil.encryptAES(originalText, password);
			History history = new History();
			history.setPassword(password);
			history.setOriginalText(originalText);
			history.setCipherText(encryptStr);
			history.setOperationType("加密");
			history.setType("文字");
			history.setUser(user);
			historyService.saveHistory(history);
			j.setCode("success");
			j.setMsg("文字加密成功");
			j.setData(encryptStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	@Override
	public AjaxJson decryptTxt(HttpServletRequest request, String cipherText, String password) {
		AjaxJson j = new AjaxJson();
		j.setCode("failure");
		j.setMsg("文字解密失败");
		try {
			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				j.setMsg("请登录");
				return j;
			}
			String decryptStr = SecurityUtil.decryptAES(cipherText, password);
			History history = new History();
			history.setPassword(password);
			history.setOriginalText(cipherText);
			history.setCipherText(decryptStr);
			history.setOperationType("解密");
			history.setType("文字");
			history.setUser(user);
			historyService.saveHistory(history);
			j.setCode("success");
			j.setMsg("文字解密成功");
			j.setData(decryptStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	@Override
	public AjaxJson encryptPic(MultipartFile file, HttpServletRequest request, String password) {
		AjaxJson j = new AjaxJson();
		j.setCode("failure");
		j.setMsg("图片加密失败");
		try {
			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				j.setMsg("请登录");
				return j;
			}
			// 判断上传文件格式
			String fileType = file.getContentType();
			logger.info("文件类型：" + fileType + "::::::加密密码为：" + password);
			if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpeg")) {
				String localPath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\encrypt\\";
				String fileName = file.getOriginalFilename();
				String suffixName = fileName.substring(fileName.lastIndexOf("."));
				fileName = UUID.randomUUID() + suffixName;
				logger.info("源文件：" + localPath + fileName);
				File dest = FileUtil.upload(file, localPath, fileName);
				String decryptPath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\decrypt\\";
				File d = new File(decryptPath);
				if (!d.exists()) {
					d.mkdir();
				}
				logger.info("加密后文件：" + decryptPath + fileName);
				AesFileUtil.encryptFile(dest, new File(decryptPath + fileName), password);
				History history = new History();
				history.setPassword(password);
				history.setOriginalText(localPath + fileName);
				history.setCipherText(decryptPath + fileName);
				history.setOperationType("加密");
				history.setType("图片");
				history.setUser(user);
				historyService.saveHistory(history);
				j.setCode("success");
				j.setMsg("图片加密成功");
				j.setData(Base64Utils.encodeToString(history.getId().getBytes()));
				Optional<History> optional = historyDao.findById(history.getId());
				if (optional.isPresent()) {
					History h = optional.get();
					h.setOriginalText(Base64Utils.encodeToString(history.getId().getBytes()));
					historyDao.save(h);
				}
			} else {
				j.setMsg("请选择图片进行加解密");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	@Override
	public AjaxJson decryptPic(HttpServletRequest request, String content, String password) {
		AjaxJson j = new AjaxJson();
		j.setCode("failure");
		j.setMsg("图片解密失败");
		try {
			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				j.setMsg("请登录");
				return j;
			}
			String id = new String(Base64Utils.decodeFromString(content));
			logger.info("解密id：" + id + "::::::解密密码：" + password);
			Optional<History> optional = historyDao.findById(id);
			if (optional.isPresent()) {
				History history = optional.get();
				String sourcePath = history.getCipherText();
				logger.info("需要解密的文件：" + sourcePath);
				File sourceFile = new File(sourcePath);
				String decryptPath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\result\\";
				File d = new File(decryptPath);
				if (!d.exists()) {
					d.mkdir();
				}
				String fileName = sourceFile.getName();
				logger.info("源文件文件名：" + fileName);
				File destFile = new File(decryptPath + fileName);
				logger.info("解密后文件路径：" + decryptPath + fileName);
				AesFileUtil.decryptFile(sourceFile, destFile, password);
				History h = new History();
				h.setPassword(password);
				h.setOriginalText(content);
				h.setCipherText(decryptPath + fileName);
				h.setOperationType("解密");
				h.setType("图片");
				h.setUser(user);
				historyService.saveHistory(h);
				j.setMsg("图片解密成功");
				j.setCode("success");
				j.setData("/img/" + fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}
}
